# -*- coding: utf-8 -*-
import requests
import logging
import json
import sys

class Client(object):

    Regions = {
        "东北-大连":"cn-northeast-1",
        "华北-北京-1":"cn-north-1",
        "华北-北京-4":"cn-north-4",
        "华东-上海-2":"cn-east-2",
        "华南-广州":"cn-south-1"
    }

    def __init__(self, region=None, username=None, password=None, domain=None):
        self.region = region
        self.username = username
        self.password = password
        self.domain = domain
        self.set_urls(self.Regions[region])
        self.get_token()

    def set_urls(self, region):
        self.iam_url = 'https://iam.%s.myhuaweicloud.com/v3/auth/tokens' % region
        self.codehub_url = 'https://codehub-ext.%s.myhuaweicloud.com' % region
        self.projectman_url = 'https://projectman-ext.%s.myhuaweicloud.com' % region
 
    def get_token(self):
        values = {
            "auth": {
                "identity": {
                    "methods": ["password"],
                    "password": {
                        "user": {
                            "name": self.username,
                            "password": self.password,
                            "domain": {"name": self.domain}
                        }
                    }
                },
                "scope": {
                    "project": {"name": self.Regions[self.region]}
                }
            }
        }
        try:
            response = requests.post(self.iam_url, json.dumps(values))
            self.token = response.headers["X-Subject-Token"]            
            return self.token
        except:
            logging.error("Has tried to access url %s, failed!", self.iam_url)
            sys.exit()

    def get_full_url(self, service, url):
        if service == 'codehub':
            request_url = self.codehub_url + url
        elif service == 'projectman':
            request_url = self.projectman_url + url
        else:
            logging.error("Error service name.")
            sys.exit()
        
        return request_url

    def get_data(self, url):
        headers = {"X-Auth-Token":"%s" %(self.token), "Content-Type":"application/json"}
        return requests.get(url, headers=headers)
    
    def post_data(self, url, data):
        headers = {"X-Auth-Token":"%s" %(self.token), "Content-Type":"application/json"}
        return requests.post(url, json.dumps(data), headers=headers)